// pages/choose/choose.js
import {get_advisorList, create_advising} from '../../utils/backend'

const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    score:5,
    advisorList:[]
},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    get_advisorList()
    wx.event.on('get_advisorList_and_save_to_global',()=>{
      //渲染当前页面
      this.setData({
        advisorList: app.globalData.advisorList
      })
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  cardClick: function (e) {//选择咨询师
    if(app.globalData.isAdvising){
      wx.showToast({
        title: '已有咨询进行中',
        icon: 'error'
      })
    }else{
      var index = e.currentTarget.dataset.index;//获取到绑定的数据
      var advisorInfo = this.data.advisorList[index]
      console.log("========== choose advisor: "+advisorInfo.name+" ==========")
      if(advisorInfo.available){//若咨询师空闲——>创建咨询，上传到服务器，跳转到chat页面
        wx.showModal({
          content: '是否向'+advisorInfo.name+'发起咨询？',
          title: '提示',
          success: (res) => {
            if(res.confirm){
              var timestamp = Date.parse(new Date())//13位
              var created = parseInt(timestamp/1000)//10位
              var nowAdvising = {//创建咨询
                start_timestamp: timestamp,
                advisorInfo: advisorInfo,
                created: created,
                ended: '',
                score: ''
              }
              create_advising(nowAdvising)//将咨询信息上传到服务器
              wx.event.on("creat_advising_and_save_to_global",()=>{
                  wx.redirectTo({//跳转到chat页面
                  url: '../chat/chat',
                })
              })
              
            }
          }
        })
      }else{
        wx.showModal({
          content: advisorInfo.name+'忙碌中，是否等待？',
          title: '提示',
          success: (res) => {
            if(res.confirm){
                wx.navigateTo({//若咨询师忙碌——>用户等待，跳转到online页面
                url: '../online/online?advisorInfoBean='+JSON.stringify(advisorInfo),
              })
            }
          },
        })
        
      }
    }
  }
})